package com.shengyuan.manage_os.base;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

import com.shengyuan.manage_os.im.common.utils.ToastUtil;
import com.shengyuan.manage_os.ui.MainActivity;
import com.shengyuan.manage_os.ui.fragment.MessageFragment;
import com.shengyuan.manage_os.ui.fragment.WorkFragment;

import java.lang.reflect.Field;

/**
 * Created by Administrator on 2016/11/15.
 */

public class BaseFragment extends Fragment{

    protected FragmentManager manager;
    protected FragmentTransaction transaction;
    protected BaseFragment currentFragment;
    private BaseFragment newFragment;
    private MessageFragment mFragment;
    private WorkFragment wFragment;

    @TargetApi(17)
    public BaseFragment(){
        super();
//        manager = MainActivity.activity.getChildFragmentManager();
        manager = MainActivity.activity.getFragmentManager();
    }

    public BaseFragment init(){
        if(currentFragment == null){
            currentFragment = new BaseFragment();
        }
        return currentFragment;
    }
    public void switchFrament(BaseFragment newFragment, Fragment currentFragment){
        transaction = manager.beginTransaction();
        if(currentFragment != null){
            transaction.hide(currentFragment);
        }

        transaction.show(newFragment);
        transaction.commit();

    }
    public void addFrament(int id,Fragment currentFragment,String tag){
        transaction = manager.beginTransaction();
        transaction.add(id,currentFragment,tag);
        transaction.commit();

    }
    public void replayFragment(int id,Fragment currentFragment,BaseFragment newFragment,String tag){
        if (currentFragment == newFragment){
            ToastUtil.showMessage("重复点击");
            return;
        }
        transaction = manager.beginTransaction();
        if (tag.equals("MESSAGE")&&newFragment!= null){
            ToastUtil.showMessage(newFragment.getId()+"");
            transaction.hide(currentFragment);
            transaction.show(newFragment);
        }else {
            transaction.replace(id, newFragment, tag);
        }
        transaction.commit();
    }

//    @Override
//    public void onDetach() {
//        super.onDetach();
//
//        try {
//            Field childFragmentManager = Fragment.class.getDeclaredField(this.getClass().getName());
//            childFragmentManager.setAccessible(true);
//            childFragmentManager.set(this, null);
//
//        } catch (NoSuchFieldException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }
//    }

}
